package com.laiyima.zhongjiang.linghuilv.demo.Serviceprovider;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.laiyima.zhongjiang.linghuilv.demo.R;
import com.laiyima.zhongjiang.linghuilv.demo.adapter.PointsAdapter;
import com.laiyima.zhongjiang.linghuilv.demo.bean.PointsBean;
import com.laiyima.zhongjiang.linghuilv.demo.util.TimeUtils;
import com.laiyima.zhongjiang.linghuilv.demo.view.ListViewPlus;

import org.json.JSONArray;
import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;

import me.imid.swipebacklayout.lib.app.SwipeBackActivity;

public class MyPointsActivity extends SwipeBackActivity implements View.OnClickListener, ListViewPlus.ListViewPlusListener {
    private String TAG = "MyPointsActivity";
    private int mpCode;
    private LinearLayout myback, show_list_points;
    private TextView toLookPoint, available_points, total_points;
    private String total, usable;


    private ListViewPlus mListView;
    private PointsBean mPointsBean;
    private PointsAdapter mPointsAdapter;
    private List<PointsBean> PointsBeanListBean = new ArrayList<>();

    private int page_index, page_count;

    @Override
    public void onRefresh() {

        mPointsAdapter.notifyDataSetChanged();

        loadData(ListViewPlus.REFRESH);
        // Log.e(TAG, "onRefresh:");

    }

    @Override
    public void onLoadMore() {
        if (page_index < page_count) {
            loadData(ListViewPlus.LOAD);
        } else {
            Toast.makeText(getBaseContext().getApplicationContext(), "已全部加载", Toast.LENGTH_SHORT).show();
            onLoadComplete();
        }
    }

    private void loadData(final int what) {
        // 这里模拟从服务器获取数据
        new Thread(new Runnable() {
            @Override
            public void run() {
                Message msg = handler.obtainMessage();
                msg.what = what;
                handler.sendMessage(msg);
            }
        }).start();
    }

    private Handler handler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case ListViewPlus.REFRESH:
                    Log.e(TAG, "onRefresh:");
                    //intView();
                    onLoadComplete();
                    Toast.makeText(getBaseContext().getApplicationContext(), "已刷新数据", Toast.LENGTH_SHORT).show();
                    break;
                case ListViewPlus.LOAD:
                    Toast.makeText(getBaseContext().getApplicationContext(), "已加载完数据", Toast.LENGTH_SHORT).show();
                    page_index++;
                    loadMode(page_index);
                    onLoadComplete();

                    break;
            }

        }

        ;
    };

    private void onLoadComplete() {
        mListView.stopRefresh();
        mListView.stopLoadMore();
        mListView.setRefreshTime(TimeUtils.getCurrentTime());
    }

    protected boolean useThemestatusBarColor = false;//是否使用特殊的标题栏背景颜色，android5.0以上可以设置状态栏背景色，如果不使用则使用透明色值

    protected void setStatusBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {//5.0及以上
            View decorView = getWindow().getDecorView();
            int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
            decorView.setSystemUiVisibility(option);
            //根据上面设置是否对状态栏单独设置颜色
            if (useThemestatusBarColor) {
                // getWindow().setStatusBarColor(getResources().getColor(R.color.colorTheme));
            } else {
                getWindow().setStatusBarColor(Color.TRANSPARENT);
            }
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {//4.4到5.0
            WindowManager.LayoutParams localLayoutParams = getWindow().getAttributes();
            localLayoutParams.flags = (WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | localLayoutParams.flags);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {//android6.0以后可以对状态栏文字颜色和图标进行修改
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_points);
        myback = (LinearLayout) findViewById(R.id.mp_back);
        myback.setOnClickListener(this);
        toLookPoint = (TextView) findViewById(R.id.view_point_details);
        toLookPoint.setOnClickListener(this);
        available_points = (TextView) findViewById(R.id.available_points);
        total_points = (TextView) findViewById(R.id.total_points);
        mListView = (ListViewPlus) findViewById(R.id.point_list);
        mListView.setRefreshEnable(true);
        mListView.setLoadEnable(true);
        mListView.setAutoLoadEnable(true);
        mListView.setRefreshTime(TimeUtils.getCurrentTime());
        mListView.setListViewPlusListener(this);

        setListener();
        show_list_points = (LinearLayout) findViewById(R.id.show_list_points);
        setStatusBar();
        intView();
        setAndroidNativeLightStatusBar(this, false);
    }

    private static void setAndroidNativeLightStatusBar(Activity activity, boolean dark) {
        View decor = activity.getWindow().getDecorView();
        if (dark) {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        } else {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        }
    }


    private void setListener() {
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                ListViewPlus listView = (ListViewPlus) parent;
                PointsBean mPointsBean = (PointsBean) listView.getItemAtPosition(position);
                String day = mPointsBean.getDay();

                Intent Taxlistintent = new Intent(MyPointsActivity.this, PointsDetailsActivity.class);
                Taxlistintent.putExtra("day", day);
                startActivity(Taxlistintent);
            }
        });
    }

    private void intView() {
        SharedPreferences sharedPreferences = getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String userID = sharedPreferences.getString("userID", "");
        RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/lfl_api/Commonlfl/point");
        //需要带入的参数
        params.addBodyParameter("uid", userID);
        params.addBodyParameter("page_size", 10);

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    mpCode = jsonObject.optInt("code", 0);
                    String data = jsonObject.optString("data", null);
                    if (!TextUtils.isEmpty(data)) {
                        JSONObject jsonObjec = new JSONObject(data);
                        page_count = jsonObjec.optInt("page_count", 0);
                        page_index = jsonObjec.optInt("page_index", 0);
                        total = jsonObjec.optString("total", "");
                        usable = jsonObjec.optString("usable", "");
                        Double a1 = Double.parseDouble(usable);
                        DecimalFormat decimalFormatq = new DecimalFormat("0.00");
                        String b1 = decimalFormatq.format(a1);
                        available_points.setText(b1);
                        Double a2 = Double.parseDouble(total);
                        String b2 = decimalFormatq.format(a2);

                        // available_points.setText(usable + "");

                        total_points.setText(b2 + "");
                    }
                    JSONObject jData = new JSONObject(data);
                    JSONArray list = jData.getJSONArray("list");
                    for (int i = 0; i < list.length(); i++) {
                        JSONObject value = list.getJSONObject(i);
                        String uid = value.getString("uid");
                        String day = value.getString("day");
                        String money = value.getString("money");
                        mPointsBean = new PointsBean(uid, day, money);
                        PointsBeanListBean.add(mPointsBean);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (mpCode == 200) {
                    mPointsAdapter = new PointsAdapter(getBaseContext().getApplicationContext(), PointsBeanListBean);
                    mPointsAdapter.notifyDataSetChanged();
                    mListView.setAdapter(mPointsAdapter);
                }

                if (mpCode == 500) {
                    Toast.makeText(getBaseContext().getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                } else {


                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e(TAG, "回调失败");
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
                if (PointsBeanListBean.size() == 0) {
                    show_list_points.setVisibility(View.VISIBLE);
                } else {
                    show_list_points.setVisibility(View.GONE);
                }
            }
        });
    }

    private void loadMode(int page_index) {
        SharedPreferences sharedPreferences = getSharedPreferences("userinfo.txt", Context.MODE_PRIVATE);
        String userID = sharedPreferences.getString("userID", "");
        RequestParams params = new RequestParams("http://zljl.laiima.com/index.php?s=/lfl_api/Commonlfl/point");
        //需要带入的参数
        params.addBodyParameter("uid", userID);
        params.addBodyParameter("page_size", 10);
        params.addBodyParameter("page_index", page_index);

        x.http().post(params, new Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONObject jsonObject = new JSONObject(result);
                    mpCode = jsonObject.optInt("code", 0);
                    String data = jsonObject.optString("data", null);
                    JSONObject jData = new JSONObject(data);
                    JSONArray list = jData.getJSONArray("list");
                    for (int i = 0; i < list.length(); i++) {
                        JSONObject value = list.getJSONObject(i);
                        String uid = value.getString("uid");
                        String day = value.getString("day");
                        String money = value.getString("money");
                        mPointsBean = new PointsBean(uid, day, money);
                        PointsBeanListBean.add(mPointsBean);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
                if (mpCode == 200) {
                    // mPointsAdapter = new PointsAdapter(getBaseContext().getApplicationContext(), PointsBeanListBean);
                    mPointsAdapter.notifyDataSetChanged();
                    //  mListView.setAdapter(mPointsAdapter);
                }

                if (mpCode == 500) {
                    Toast.makeText(getBaseContext().getApplicationContext(), "系统异常", Toast.LENGTH_SHORT).show();
                } else {


                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                Log.e(TAG, "回调失败");
            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {
            }
        });
    }


    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.mp_back:
                finish();
                break;
            case R.id.view_point_details:
//                Intent isintent = new Intent(MyPointsActivity.this, PointsDetailsActivity.class);
//                startActivity(isintent);
                break;
        }
    }
}
